import Vue from 'vue'
import App from './App.vue'

Vue.prototype.$dispatch = function (eventName, componentName, value) {
  let parent = this.$parent
  while (parent) {
    if (parent.$options.name === componentName) {
      parent.$emit(eventName, value)
      break
    }
    parent = parent.$parent
  }
}

Vue.prototype.$broadcast = function (eventName, componentName, value) {
  const children = this.$children
  function broadcast(children) {
    for (let i = 0; i < children.length; i++) {
      const child = children[i]
      if (child.$options.name === componentName) {
        child.$emit(eventName, value)
        return
      } else {
        if (child.$children) {
          broadcast(child.$children)
        }
      }
    }
  }
  broadcast(children)
}

new Vue({
  name: 'Root',
  el: '#app',
  render: (h) => h(App)
})

/**
  .vue 文件是在编译阶段 通过 vue-loader 编译成 render 函数
  而 template 模板是在应用运行时编译的
 */
